package com.epfresh.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.epfresh.R;
import com.epfresh.adapter.*;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.LoadMoreExpandableListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.*;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookGoodsMonthActivity extends BaseActivity  implements LoadMoreExpandableListView.IXListViewListener {
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    private TagPager tagPager = new TagPager();
    //Context mContext;

    private LoadMoreExpandableListView lvContent;
    private List<BookGoodsMonth.ListBean> list = new ArrayList<>();
    BookGoodsMonthExpandListAdapter adapter;
    String nameTitle,timeValue,categoryIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_book_pay_month);
        nameTitle = getIntent().getStringExtra("nameTitle");
        timeValue = getIntent().getStringExtra("timeValue");
        categoryIds = getIntent().getStringExtra("categoryIds");
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText(nameTitle+"消费明细");
        initView();
        adapter = new BookGoodsMonthExpandListAdapter(this,lvContent,list);
        lvContent.setAdapter(adapter);
        loadData(tagPager.getNumber());
    }
    void initView(){

        initHeadView();
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        lvContent = (LoadMoreExpandableListView)findViewById(R.id.lv_content);
        lvContent.setPullLoadEnable(true);
        lvContent.setXListViewListener(this);
        lvContent.setGroupIndicator(null);

    }
    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        lvContent.resetNoMore();
        refreshFlag = true;
        loadData(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }

    void loadData(int page){
        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        map.put("queryDate", timeValue);
        map.put("categoryIds", categoryIds);
        map.put("pageSize","5");
        map.put("pageNumber",""+page);
        map.put("accountId", getUser().getAccountId());
        entity.setCmd(AppPurchaseRouterConstant.cmd_order_income_incomeForCategoryMonth);
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = AppPurchaseRouterConstant.cmd_order_income_incomeForCategoryMonth;
        requestTag.action = page;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    OnRequestListener<BookGoodsMonth> onRequestListener = new OnRequestListener<BookGoodsMonth>() {
        @Override
        public BookGoodsMonth jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BookGoodsMonth.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<BookGoodsMonth> response, Object tag) {
            hideProgressDialog();

            showMainView();
            requestSucceedCount ++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                list.clear();
            }
            BookGoodsMonth orderResponse = response.getResponseElement();
            List<BookGoodsMonth.ListBean> content = orderResponse.getList();
            tagPager.setLast(orderResponse.isIsLastPage());
            tagPager.setNumber(orderResponse.getPageNumber());
            tagPager.setSize(orderResponse.getPageSize());
            tagPager.setTotalElements(orderResponse.getTotalSize());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if(orderResponse.getPageNumber()==0){
                if(refreshFlag) {
                    lvContent.setSelection(0);
                    refreshFlag=false;
                }
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };
    @Override
    public void onResume() {
        super.onResume();
    }

}
